package com.lst.servlet;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.AnswerReqPara;
import com.lst.entity.response.AnswerResPara;
import com.lst.model.Answer;
import com.lst.model.JiluLog;
import com.lst.service.AnswerService;
import com.lst.service.ClientNumService;
import com.lst.service.JiluLogService;
import com.lst.service.MstDiscussService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: AnswerDetailServlet
 * @Description: 回答添加接口
 * 
 */
public class AnswerDetailServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private AnswerService answerService = ctx.getBean(AnswerService.class);
	
    private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	
	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);
	
	private JiluLogService jiluLogService = ctx.getBean(JiluLogService.class);
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		
		AnswerResPara resPara = new AnswerResPara();

		try {
			AnswerReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
     		Integer userid = Integer.valueOf(reqPara.getUserid());
			Integer answerId = Integer.valueOf(reqPara.getAnswerId());					
			
			Answer answer=answerService.selectByPrimaryKey(answerId);
			if(answer!=null){
				//转换时间格式
				Date date=answer.getAnswerCreateDate();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String str=sdf.format(date);
				answer.setAnswerCreateDate2(DateUtil.changeTime(str));
				
				  //标识是否收藏
				Map<String, Object> fmap = new HashMap<String, Object>();
				fmap.put("enabled", true);
				fmap.put("isdeleted", false);
				fmap.put("clientid", userid);
				fmap.put("actid", answer.getAnswerId());
				fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_ANSWER);
				fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
				Integer count = clientNumService.queryCountByMap(fmap);
				if(count>0){
					answer.setIsFavorite(true);
				}else{
					answer.setIsFavorite(false);
				}
				
				//收藏量
				Integer favoriteNum = CommFunUtils.opNum(null, answer.getAnswerId(), CommCode.SYSTEM_CARESEL_RANGE_ANSWER, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
				//分享量
				Integer shareNum = CommFunUtils.opNum(null, answer.getAnswerId(), CommCode.SYSTEM_CARESEL_RANGE_ANSWER, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
				answer.setAnswerFavoriteNum(favoriteNum);
				answer.setAnswerShareNum(shareNum);

				//评论量
				Map<String, Object> anmap = new HashMap<String, Object>();
				anmap.put("enabled", true);
				anmap.put("isdeleted", false);
				anmap.put("tarid", answerId);
				anmap.put("type", CommCode.SYSTEM_CARESEL_RANGE_ANSWER);
				Integer answerDiscussNum = mstDiscussService.queryCountByMap(anmap);
				answer.setAnswerDiscussNum(answerDiscussNum);
				
				//喜欢数量
				Map<String, Object> jlmap2 = new HashMap<String, Object>();
				jlmap2.put("sourceId", answerId);
				jlmap2.put("jiluType", CommCode.SYSTEM_CARESEL_LOVE_ANSWER);
				int loveNum=jiluLogService.countBySourceId(jlmap2);
				answer.setAnswerLoveNum(loveNum);
				
				//喜欢标识
				Map<String, Object> jilumap = new HashMap<String, Object>();
				jilumap.put("jiluType", CommCode.SYSTEM_CARESEL_LOVE_ANSWER);
				jilumap.put("isDelete", false);
				jilumap.put("sourceId", answerId);
				jilumap.put("createUser", userid);
				JiluLog jilu=jiluLogService.queryByMap(jilumap);
				if(jilu!=null){
					answer.setIsLove(jilu.getIsLove());
				}
				
				//对该回答喜欢的所有人详情
				Map<String, Object> jlmap = new HashMap<String, Object>();
				jlmap.put("jiluType", CommCode.SYSTEM_CARESEL_LOVE_ANSWER);
				jlmap.put("isDelete", false);
				jlmap.put("isLove", true);
				jlmap.put("sourceId", answerId);
				jlmap.put("orderByClause", "md.createDate desc");
				PageBounds pagebounds = new PageBounds(1,6);
				List<JiluLog> jiluList=jiluLogService.queryByList(jlmap, pagebounds);
				
				resPara.setAnswer(answer);
				resPara.setJiluList(jiluList);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}else{
				resPara.setCode(CommCode.M_A000001);
            	resPara.setMessage(CommCode.M_A000002);
			}
			
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public AnswerReqPara getReqPara(HttpServletRequest request) {

		AnswerReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new AnswerReqPara());

			reqPara = (AnswerReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String answerId = request.getParameter("answerId");

	        reqPara.setAnswerId(answerId);
	        reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		AnswerReqPara cdReqPara = (AnswerReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getAnswerId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("回答id为空");
		}else if (StringUtils.isEmpty(cdReqPara.getUserid())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}

		return  flag;
	}

}
